package com.hqyj.web.filter;

import com.hqyj.pojo.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author cz
 * 2021/8/12 18:07
 */
@WebFilter(urlPatterns = {"*.jsp","*.do"})
public class UserLoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String uri = request.getRequestURI();
        if (uri.indexOf("index.jsp") != -1 || uri.indexOf("login.do") != -1 || uri.indexOf("register.do") != -1 || uri.indexOf("modifyPassword.do") != -1 || uri.indexOf("updatepassword.jsp") != -1){
            filterChain.doFilter(servletRequest, servletResponse);
        }else {
            HttpSession session = request.getSession();
            User user = (User) session.getAttribute("user");
            if (user != null){
                filterChain.doFilter(servletRequest, servletResponse);
            }else{
                request.setAttribute("msg","请登录之后进行访问。。。");
                request.getRequestDispatcher("/index.jsp").forward(servletRequest, servletResponse);
            }
        }
    }

    @Override
    public void destroy() {

    }
}
